﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using CaptchaLearning.Infrastructure.Model;

namespace CaptchaLearning.Infrastructure.Service
{
    public class XmlService : IXmlService
    {
        private readonly static Type[] _knowTypes = new[]
            {
                typeof(Project),
                typeof(TransitionMatrix),
                typeof(Character),
                typeof(ImageColumn),
                typeof(EmissionMatrix)
            };

        public Model.Project LoadProject(string path)
        {
            string content = File.ReadAllText(path);
            Project project = SerializationService.ToObject<Project>(content, _knowTypes);
            return project;
        }

        public bool SaveProject(Model.Project project, string path)
        {
            try
            {
                string xml = SerializationService.ToXml<Project>(project, _knowTypes);
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xml);

                if (!Directory.Exists(Path.GetDirectoryName(path)))
                    Directory.CreateDirectory(Path.GetDirectoryName(path));

                xmlDocument.Save(path);

                return true;
            }
            catch (UnauthorizedAccessException accessException)
            {
                LogService.WriteLog("DocumentService.cs", "SaveProject", accessException.Message);
            }
            catch (Exception ex)
            {
                LogService.WriteLog("DocumentService.cs", "SaveProject", ex.Message);
            }

            return false;
        }
    }
}
